package com.sopaths.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Named;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.springframework.util.StringUtils;

import com.sopaths.contract.domain.SearchRecruitment;
import com.sopaths.contract.service.SearchService;
import com.sopaths.utility.properties.ApplicationProperties;

@Named
public class SearchServiceImpl implements SearchService {

	private static String solrServerIp;
	private static String solrServerPort;
	private static String solrServerInstance;
	private static StringBuffer solrServerUrl;
	private static String solrPreferredLanguage;

	private SolrServer solrServer;
	private QueryResponse queryResponse;

	static {
		solrServerInstance = ApplicationProperties.getSolrServerInstance();
		solrServerPort = ApplicationProperties.getSolrServerPort();
		solrServerIp = ApplicationProperties.getSolrServerIp();
		solrPreferredLanguage = ApplicationProperties.getSolrGeoLanguage();
		solrServerUrl = new StringBuffer();
		solrServerUrl.append("http://").append(solrServerIp).append(":")
				.append(solrServerPort).append("/solr/")
				.append(solrServerInstance);
	}

	@Override
	public Map<String, Object> searchRecruitment(Map<String, String> parameters) {

		Map<String, Object> result = new HashMap<String, Object>();

		// TODO Auto-generated method stub
		StringBuilder parameterQ = new StringBuilder();

		String primaryLocation = parameters.get("primaryLocation");
		String jobTitile = parameters.get("jobTitile");
		String workExperence = parameters.get("workExperence");

		/*
		 * define the query paramenter url
		 */
		if (!StringUtils.isEmpty(primaryLocation)) {
			parameterQ.append("r_primary_location:").append(primaryLocation)
					.append("AND");
		}

		if (!StringUtils.isEmpty(jobTitile)) {
			parameterQ.append("r_job_title:").append(jobTitile).append("AND");
		}

		if (!StringUtils.isEmpty(workExperence)) {
			parameterQ.append("r_experence:").append(workExperence)
					.append("AND");
		}

		String queryURL = this.convertQueryURL(parameterQ.toString());
		SolrQuery query = new SolrQuery();

		query.setQuery(queryURL);

		/*
		 * sort logic
		 */
		String sortColumn = parameters.get("sortColumn");
		String sortType = parameters.get("sortType");
		this.addSortColumn(query, sortColumn, sortType);

		/*
		 * paging
		 */
		if (org.apache.commons.lang.StringUtils.isNotBlank(parameters
				.get("pageNo"))) {
			Integer pageSize = parameters.get("pageSize") == null ? 20
					: Integer.valueOf(parameters.get("pageSize"));

			Integer pageNo = Integer.valueOf(parameters.get("pageNo"));
			query.setStart((pageNo - 1) * pageSize);
			query.setRows(pageSize);
		}

		/*
		 * highlight
		 */
		query.setHighlight(true); // 开启高亮组件
		query.addHighlightField("r_job_title");// 高亮字段
		query.setHighlightSimplePre("<font color='red'>");// 标记，高亮关键字前缀
		query.setHighlightSimplePost("</font>");// 后缀

		/*
		 * handler result
		 */

		QueryResponse solrResult = this.solrQuery(query);
		List<SearchRecruitment> recruiments = solrResult
				.getBeans(SearchRecruitment.class);
		result.put("recruiments", recruiments);

		return result;
	}

	public QueryResponse solrQuery(SolrQuery query) {

		queryResponse = new QueryResponse();
		solrServer = new HttpSolrServer(solrServerUrl.toString());
		try {
			queryResponse = solrServer.query(query);
		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return queryResponse;
	}

	private void addSortColumn(SolrQuery solrQuery, String sortColumn,
			String sortType) {
		if (org.apache.commons.lang.StringUtils.equals(sortType, "desc")) {
			solrQuery.addSort(sortColumn, SolrQuery.ORDER.desc);
		} else {
			solrQuery.addSort(sortColumn, SolrQuery.ORDER.asc);
		}
	}

	/**
	 * @param oldExpression
	 * @return
	 */
	private String convertQueryURL(String oldExpression) {
		String lastExpression;
		lastExpression = oldExpression.replace("AND", " AND ")
				.replace("NOT", " NOT ").replace("OR", " OR ");

		if (lastExpression.endsWith("AND ")) {
			lastExpression = lastExpression.substring(0,
					lastExpression.length() - 5);
		} else if (lastExpression.endsWith("OR ")) {

		}
		return lastExpression;
	}
}
